package com.zhl.scheduling.service.impl;

import com.zhl.scheduling.common.manger.LoginStatusManager;
import com.zhl.scheduling.mapper.UserMapper;
import com.zhl.scheduling.model.bo.LoginStatusBO;
import com.zhl.scheduling.model.entity.User;
import com.zhl.scheduling.model.vo.ResStatus;
import com.zhl.scheduling.model.vo.ResultVO;
import com.zhl.scheduling.service.UserService;
import com.zhl.scheduling.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * @Author: ZhangLu In DLUT
 * @since: 1.0.0
 * @Description: 用户登录登出接口实现类
 */
@Service
public class UserServiceImpl implements UserService {

    /**
     * 在service中mapper层的接口指向实现类
     */
    @Resource
    private UserMapper userMapper;

    @Autowired
    private HttpSession session;

    /**
     * 验证登录
     * @param username 用户名
     * @param password 用户密码
     * @param userType 用户类型
     * @return ResultVO 用作封装数据给前端的数据
     */
    @Override
    public ResultVO checkLogin(String username, String password, Integer userType) {

        // 1、根据用户名和角色查询账户信息
        // 封装查询条件
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", username)
                .andEqualTo("userRole", userType)
                .andEqualTo("userStatus", 1);
        User user = userMapper.selectOneByExample(example);

        // 2、判断
        if (user == null) {
            // 用户名不存在
            return new ResultVO(ResStatus.NO, "用户不存在", null);
        }else {
            // 3、对输入的密码进行校验
            if (user.getPassword().equals(MD5Utils.md5(password))) {
                //  验证成功
                LoginStatusBO loginStatusBO = LoginStatusBO.fromUserInfo(user);
                // 设置session以便查询登录状态
                LoginStatusManager.setLoginStatus(session, loginStatusBO);
                return new ResultVO(ResStatus.OK, "登录成功", loginStatusBO);
            }else {
                return new ResultVO(ResStatus.NO, "密码错误", null);
            }
        }
    }

    /**
     * 获取用户的登录状态信息
     * @return ResultVO 用作封装数据给前端的数据
     */
    @Override
    public ResultVO getLoginStatus(){
        LoginStatusBO loginStatus = LoginStatusManager.getLoginStatus(session);
        if (loginStatus.getLoggedIn()) {
            return new ResultVO(ResStatus.OK, "登录状态正常", loginStatus);
        }else {
            return new ResultVO(ResStatus.NO, "登录状态失效", loginStatus);
        }
    }

    /**
     * 提供用户登出信息，并设置相关用户状态
     * @return ResultVO 用作封装数据给前端的数据
     */
    @Override
    public ResultVO logout() {
        LoginStatusManager.setLoginStatus(session, null);
        return new ResultVO(ResStatus.NO, "登录状态失效", null);
    }
}
